package com.yami.shop.security.platform.util;

import com.yami.shop.security.comment.exception.UnauthorizedException;
import com.yami.shop.security.platform.model.YamiSysUser;
import lombok.experimental.UtilityClass;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;

/**
 *
 * @author LGH
 */
@UtilityClass
public class SecurityUtils {


    /**
     * 获取用户
     */
    public YamiSysUser getSysUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        if (authentication == null) {
            // 无法获取用户信息
            throw new UnauthorizedException("yami.user.no.exist");
        }

        if (!(authentication instanceof OAuth2Authentication)) {
            // 无法获取用户信息
            throw new UnauthorizedException("yami.user.no.exist");
        }
        OAuth2Authentication oAuth2Authentication = (OAuth2Authentication)authentication;

        YamiSysUser details = (YamiSysUser) oAuth2Authentication.getUserAuthentication().getDetails();
        if (details == null) {
            // 无法获取用户信息
            throw new UnauthorizedException("yami.user.no.exist");
        }
        return details;
    }
}
